import fetch from 'node-fetch';

// 基础URL
const BASE_URL = 'http://localhost:3000/api/v1';
const TEST_USERNAME = `testuser_${Date.now()}`;
const TEST_EMAIL = `${TEST_USERNAME}@example.com`;
const TEST_PASSWORD = 'Test@1234';
let JWT_TOKEN = '';

// 打印分隔线
const printSeparator = () => {
  console.log('\n========================================\n');
};

// 测试函数
const testApi = async (description, method, endpoint, data, authToken) => {
  console.log(`测试: ${description}`);
  console.log(`端点: ${method} ${endpoint}`);
  if (data) {
    console.log(`请求体: ${JSON.stringify(data)}`);
  }

  const headers = {
    'Content-Type': 'application/json'
  };

  if (authToken) {
    headers['Authorization'] = `Bearer ${authToken}`;
  }

  try {
    const response = await fetch(`${BASE_URL}${endpoint}`, {
      method,
      headers,
      body: data ? JSON.stringify(data) : undefined
    });

    const responseData = await response.json().catch(() => ({}));
    console.log(`状态码: ${response.status}`);
    console.log(`响应: ${JSON.stringify(responseData, null, 2)}`);
    return { status: response.status, data: responseData };
  } catch (error) {
    console.error(`请求失败: ${error.message}`);
    return { status: 500, data: { error: error.message } };
  }
};

// 主测试函数
const runTests = async () => {
  try {
    // 测试健康检查
    printSeparator();
    console.log('测试健康检查...');
    await testApi('健康检查', 'GET', '/health');

    // 测试用户注册
    printSeparator();
    console.log('测试用户注册...');
    const registerData = {
      username: TEST_USERNAME,
      password: TEST_PASSWORD,
      email: TEST_EMAIL,
      name: '测试用户',
      role: 'student'
    };
    const registerResponse = await testApi('用户注册', 'POST', '/auth/register', registerData);

    // 测试用户登录
    printSeparator();
    console.log('测试用户登录...');
    const loginData = {
      email: TEST_EMAIL,
      password: TEST_PASSWORD
    };
    const loginResponse = await testApi('用户登录', 'POST', '/auth/login', loginData);

    // 从登录响应中提取token
    if (loginResponse.data && loginResponse.data.token) {
      JWT_TOKEN = loginResponse.data.token;
      console.log(`成功获取JWT令牌: ${JWT_TOKEN.substring(0, 20)}...`);
    } else {
      console.log('无法获取JWT令牌');
    }

    // 测试获取当前用户信息
    printSeparator();
    console.log('测试获取当前用户信息...');
    await testApi('获取当前用户信息', 'GET', '/users/me', null, JWT_TOKEN);

    // 测试获取所有课程
    printSeparator();
    console.log('测试获取所有课程...');
    const coursesResponse = await testApi('获取所有课程', 'GET', '/courses', null, JWT_TOKEN);

    // 从课程列表中提取第一个课程ID
    let courseId = 1;
    if (coursesResponse.data && Array.isArray(coursesResponse.data.data)) {
      const firstCourse = coursesResponse.data.data[0];
      if (firstCourse && firstCourse.id) {
        courseId = firstCourse.id;
        console.log(`找到课程ID: ${courseId}`);
      } else {
        console.log(`未找到课程ID，使用默认值: ${courseId}`);
      }
    }

    // 测试选课
    printSeparator();
    console.log('测试选课...');
    const enrollData = { courseId };
    await testApi('选课', 'POST', '/enrollments', enrollData, JWT_TOKEN);

    // 测试获取我的选课
    printSeparator();
    console.log('测试获取我的选课...');
    await testApi('获取我的选课', 'GET', '/enrollments/me', null, JWT_TOKEN);

    // 测试获取所有用户（需要管理员权限）
    printSeparator();
    console.log('测试获取所有用户（需要管理员权限）...');
    await testApi('获取所有用户', 'GET', '/users', null, JWT_TOKEN);

    // 测试登出
    printSeparator();
    console.log('测试用户登出...');
    await testApi('用户登出', 'POST', '/auth/logout', null, JWT_TOKEN);

  } catch (error) {
    console.error('测试过程中发生错误:', error);
  } finally {
    console.log('\n测试完成！');
  }
};

// 运行测试
runTests();
